package com.khotyn.heresy.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.khotyn.heresy.bean.HeresyErrorMessage;
import com.khotyn.heresy.bean.PictureDetail;
import com.khotyn.heresy.bean.Tag;
import com.khotyn.heresy.exception.IllegalUrlParamException;
import com.khotyn.heresy.service.PictureEditService;
import com.khotyn.heresy.util.ListOperation;
import com.khotyn.heresy.validator.PictureEditValidator;

/**
 * 图片编辑控制类
 * 
 * @author 黄挺
 */
@Controller
@RequestMapping("/pictureEdit.html")
public class PictureEditController {
	@Autowired
	private PictureEditService pictureEditService; // 图片编辑服务类
	private List<Tag> pictureTags; // 图片标签，用于保存图片标签

	@RequestMapping(method = RequestMethod.POST)
	public ModelAndView onSubmit(@ModelAttribute("picture") PictureDetail picture, BindingResult result, HttpServletRequest request, ModelMap map) {
		String requestUrl = request.getRequestURL().toString();
		String tagString = request.getParameter("pictureTags");
		picture.setPictureTags(getPictureTags());

		// 验证标签的合法性
		List<String> tags = ListOperation.stringToList(tagString, "\\s{1,}");

		if (ListOperation.filtList(tags)) {
			map.addAttribute("tagError", true);
			return new ModelAndView("pictureEdit");
		}
		// 验证提交信息的合法性
		int oldErrorCount = result.getErrorCount();
		new PictureEditValidator().validate(picture, result);
		int newErrorCount = result.getErrorCount();

		if (oldErrorCount != newErrorCount) {
			return new ModelAndView("pictureEdit");
		}
		pictureEditService.doService(picture, tags, requestUrl);

		return new ModelAndView("redirect:/picture.html?pictureID=" + picture.getPictureID());
	}

	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView onLoad(HttpSession session, ModelMap model, @RequestParam(value = "pictureID", required = false) String pictureID,
			@RequestParam(value = "ownerID", required = false) String ownerIDStr) {
		Integer userID = (Integer) session.getAttribute("userID");

		try {
			validate(pictureID, ownerIDStr, userID);
		} catch (IllegalUrlParamException e) {
			return e.getErrorModel();
		}

		PictureDetail picture = pictureEditService.getPictureDAO().selectPicByPicID(pictureID);
		setPictureTags(picture.getPictureTags());
		model.addAttribute("picture", picture);

		return new ModelAndView("pictureEdit", "picture", picture);
	}

	private void validate(String pictureID, String ownerIDStr, Integer userID) throws IllegalUrlParamException {
		HeresyErrorMessage message = null;

		if (!NumberUtils.isDigits(ownerIDStr) || !NumberUtils.isDigits(pictureID)) {
			message = new HeresyErrorMessage("非法的参数", "操作失败", "/Dragonfly/");
		} else if (userID == null || (userID != NumberUtils.toInt(ownerIDStr) && NumberUtils.toInt(ownerIDStr) != 0)) {
			message = new HeresyErrorMessage("您不是这样图片的所有者，无法编辑这张图片", "权限不够", "/Dragonfly/picture.html?pictureID=" + pictureID);
		}

		if (message != null) {
			throw new IllegalUrlParamException(message);
		}
	}

	public void setPictureTags(List<Tag> pictureTags) {
		this.pictureTags = pictureTags;
	}

	public List<Tag> getPictureTags() {
		return pictureTags;
	}
}
